<template>
<div class="product-create">
    <form id="form">
        <div class="weui-cells">
            <div class="weui-cell weui-cells_form" id="uploader"> 
                <div class="weui-cell__bd"> 
                    <div class="weui-uploader"> 
                        <div class="weui-uploader__hd"> 
                            <p class="weui-uploader__title">货品图片</p> 
                            <div class="weui-uploader__info">
                                <span id="uploadCount">0</span>/8
                            </div> 
                        </div> 
                        <div class="weui-uploader__bd"> 
                            <ul class="weui-uploader__files" id="uploaderFiles">
                                <li v-for="(img, index) in uploadedList" :key="index" :data-ex="index" class="weui-uploader__file" :style="{backgroundImage: 'url(' + imageBaseUrl + img + ')'}">  </li>
                            </ul> 
                            <div class="weui-uploader__input-box"> 
                                 <!-- capture="camera" -->
                                <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple=""> 
                            </div> 
                        </div> 
                    </div> 
                </div> 
            </div>

            <div class="weui-cell">
                <div class="weui-cell__hd"><label for="" class="weui-label">货品名称</label></div>
                <div class="weui-cell__bd">
                    <input @click="selectProd" v-model="form.product_name" class="weui-input" type="text" value="weui input error" readonly required placeholder="选择货品">
                </div>
            </div>

            <div class="weui-cell">
                <div class="weui-cell__hd"><label for="" class="weui-label">货品规格</label></div>
                <div class="weui-cell__bd">
                    <input v-model="form.product_spec" class="weui-input" type="text" placeholder="请输入货品规格">
                </div>
            </div>

            <div class="weui-cell">
                <div class="weui-cell__hd"><label for="" class="weui-label">货品单价</label></div>
                <div class="weui-cell__bd">
                    <input v-model="form.product_price" class="weui-input" type="number" pattern="[0-9]*" required placeholder="最多两位小数">
                </div>

                <div class="weui-cell__ft">
                    <select v-model="form.product_unit" class="weui-select" required name="unitSelect">
                        <option v-for="unit in unitSelect" :key="unit" :value="unit">元/{{ unit }}</option>
                    </select>
                </div>
            </div>

            <div class="weui-cell">
                <div class="weui-cell__hd"><label for="" class="weui-label">发货地址</label></div>
                <div class="weui-cell__bd">
                    <input v-model="form.product_address" class="weui-input" type="text" placeholder="请填写发货地址">
                </div>
            </div>

            <div class="weui-cell">
                <div class="weui-cell__hd"><label for="" class="weui-label">物流方式</label></div>
                <div class="weui-cell__bd">
                    <input v-model="form.product_logistics" class="weui-input" type="text" placeholder="物流方式">
                </div>
            </div>

            <div class="weui-cell" style="align-items: flex-start;" >
                <div class="weui-cell__hd"><label for="" class="weui-label">货品描述</label></div>
                <div class="weui-cell__bd">
                    <textarea v-model="form.product_description" class="weui-textarea" placeholder="货品描述" rows="3"></textarea>
                </div>
            </div>

        </div>
    </form>

    <div class="action">
        <a @click="submitHandle" href="javascript:;" class="weui-btn weui-btn_primary">{{ this.id ? '保存修改' : '确认发布' }}</a>
    </div>
    <div v-if="this.id" class="action action-delete">
        <a @click="destory" href="javascript:;" class="weui-btn">删除货品</a>
    </div>

</div>
</template>

<script>
export default {
    props: ['id'],
    data() {
        return {
            form: {
                product_name: null,
                product_spec: null,
                product_price: null,
                product_unit: '斤',
                product_address: null,
                product_logistics: null,
                product_pics: [],
                product_description: null,
                cate_id: 0,
            },
            imageBaseUrl: '/',
            uploadList: [],
            uploadedList: [],
            unitSelect: [
                "斤",
                "公斤",
                "箱",
                "件",
                "包",
                "袋",
                "千克",
                "吨"
            ],
            submintLoading: false,
            submit: false,
            loading: false,
        }
    },
    methods: {
        // 选择分类
        selectProd() {
            // 级联picker
            let _this = this;
            weui.picker(
            [
                {
                label: "龙虾",
                value: 0,
                children: [
                    {
                    label: "大龙虾",
                    value: 1
                    },
                    {
                    label: "小龙虾",
                    value: 2
                    },
                    {
                    label: "澳洲龙虾",
                    value: 3
                    }
                ]
                },
                {
                label: "螃蟹",
                value: 1,
                children: [
                    {
                    label: "大螃蟹",
                    value: 1
                    },
                    {
                    label: "中螃蟹",
                    value: 2
                    },
                    {
                    label: "小螃蟹",
                    value: 3
                    }
                ]
                },
                {
                label: "笼子",
                value: 3,
                children: [
                    {
                    label: "大笼子",
                    value: 1
                    },
                    {
                    label: "小笼子",
                    value: 2
                    }
                ]
                },
                {
                label: "饵料",
                value: 3,
                children: [
                    {
                    label: "大饵料",
                    value: 1
                    },
                    {
                    label: "小饵料",
                    value: 2
                    }
                ]
                }
            ],
            {
                className: "custom-classname",
                container: "body",
                defaultValue: [0, 1],
                onChange: function(result) {
                console.log(result);
                },
                onConfirm: function(result) {
                let name = [];
                result.forEach(ele => {
                    name.push(ele.label);
                    _this.form.cate_id = ele.value;
                });
                _this.form.product_name = name.join(" ");
                },
                id: "doubleLinePicker"
            }
            );
        },
        submitHandle() {
            let self = this;
            if (this.submit) {
                return false
            }
            this.submit = true
            weui.form.validate('#form', function (error) {
                if (!error) {
                    self.submintLoading = weui.loading('提交中...');
                    self.uploadList.forEach(ele => {
                        if (ele.status === "success") {
                            self.form.product_pics.push(ele.res.name)
                        }
                    });

                    self.uploadedList.forEach(ele => {
                        self.form.product_pics.push(ele)
                    });

                    if (self.id) {
                        self.update()
                    } else {
                        self.publish()
                    }
                }
                // return true; // 当return true时，不会显示错误
            });
        },
        // 发布货品
        publish() {
            let self = this;
            axios.post('/member/mstore/product', self.form).then(res => {
                res = res.data
                self.submintLoading.hide();
                if (res.status === 'success') {
                    weui.toast(res.message, 1000);
                    window.location.href = '/member/mstore';
                }else {
                    weui.alert(res.message);
                }
            }).catch(err => {
                    weui.alert(res.message);
            })
        },
        // 更新货品
        update() {
            let self = this;
            axios.put('/member/mstore/product/' + this.id, self.form).then(res => {
                this.submit = false
                res = res.data
                self.submintLoading.hide();
                if (res.status === 'success') {
                    weui.toast(res.message, 1000);
                    window.location.href = '/member/mstore';
                }else {
                    weui.alert(res.message);
                }
            }).catch(err => {
                this.submit = false
                weui.alert(err.message);
            })
        },
        // 删除货品
        destory() {
            this.submit = false
            if (this.submit) {
                return false
            }
            this.submit = true
            this.submintLoading = weui.loading('正在删除...');
            axios.delete('/member/mstore/product/' + this.id).then(res => {
                this.submit = false
                res = res.data
                this.submintLoading.hide();
                if (res.status === 'success') {
                    weui.toast(res.message, 1000);
                    window.location.href = '/member/mstore';
                }else {
                    weui.alert(res.message);
                }
            }).catch(err => {
                console.log(err)
            })          
        },
        getProduct() {
            this.loading = weui.loading('正在加载')
            axios.get('/product/detail/' + this.id, {
                params: {
                    owner: 1
                }
            }).then(res => {
                this.submit = false
                let prod = res.data.data
                this.form.product_name = prod.name
                this.form.product_spec = prod.spec
                this.form.product_price = prod.price
                this.form.product_address = prod.address
                this.form.product_logistics = prod.logistics_mode
                this.form.product_description = prod.info
                this.form.cate_id = 0

                this.imageBaseUrl = prod.image_base_url                
                this.uploadedList = prod.pic_group

                this.loading.hide()
            }).catch(err => {
                this.submit = false
                console.log(err)
            })
        }
    },
    created() {
        this.id && this.getProduct()
    },
    mounted() {
        let _this = this;
        let uploadCount = 0;
        var uploadCountDom = document.getElementById("uploadCount");
        weui.uploader('#uploader', {
            url: '/public/upload',
            auto: true,
            type: 'file',
            fileVal: 'file',
            compress: {
                width: 800,
                height: 800,
                quality: .8
            },
            onBeforeQueued: function(files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if(["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0){
                    weui.alert('请上传图片');
                    return false; // 阻止文件添加
                }
                if(this.size > 10 * 1024 * 1024){
                    weui.alert('请上传不超过10M的图片');
                    return false;
                }
                if (files.length > 8) { // 防止一下子选择过多文件
                    weui.alert('最多只能上传5张图片，请重新选择');
                    return false;
                }
                if (uploadCount + 1 > 8) {
                    weui.alert('最多只能上传5张图片');
                    return false;
                }
                ++uploadCount;
                uploadCountDom.innerHTML = uploadCount;
            },
            onQueued: function(){
                _this.uploadList.push(this);
                console.log(_this.uploadList)
                // console.log(this);

                // console.log(this.status); // 文件的状态：'ready', 'progress', 'success', 'fail'
                // console.log(this.base64); // 如果是base64上传，file.base64可以获得文件的base64

                // this.upload(); // 如果是手动上传，这里可以通过调用upload来实现；也可以用它来实现重传。
                // this.stop(); // 中断上传

                // return true; // 阻止默认行为，不显示预览图的图像
            },
            onBeforeSend: function(data, headers){
                let token = document.head.querySelector('meta[name="csrf-token"]')
                $.extend(headers, { 'X-CSRF-TOKEN':  token.content }); // 可以扩展此对象来控制上传参数
                // $.extend(headers, { Origin: 'http://127.0.0.1' }); // 可以扩展此对象来控制上传头部

                // return false; // 阻止文件上传
            },
            onProgress: function(procent){

                // console.log(this, procent);
                // return true; // 阻止默认行为，不使用默认的进度显示
            },
            onSuccess: function (ret) {
                this.res = ret.data
                return false
                // return true; // 阻止默认行为，不使用默认的成功态
            },
            onError: function(err){
                // console.log(this, err);
                // return true; // 阻止默认行为，不使用默认的失败态
            }
        });
        // 缩略图预览
        document.querySelector('#uploaderFiles').addEventListener('click', function (e) {
            var target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            var url = target.getAttribute('style') || '';
            var id = target.getAttribute('data-id');

            if (url) {
                url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '');
            }
            var gallery = weui.gallery(url, {
                className: 'custom-name',
                onDelete: function onDelete() {
                    weui.confirm('确定删除该图片？', function () {
                        --uploadCount;
                        uploadCountDom.innerHTML = uploadCount;
                        
                        let ex_index = target.getAttribute('data-ex');
                        if (ex_index) {
                            _this.uploadedList.splice(ex_index, 1);
                        } else {
                            for (var i = 0, len = _this.uploadList.length; i < len; ++i) {
                                var file = _this.uploadList[i];
                                if (file.id == id) {
                                    file.stop();
                                    _this.uploadList.splice(i, 1);
                                    break;
                                }
                            }
                        }
                        target.remove();
                        gallery.hide();
                    });
                }
            });
        });
    }
};
</script>

<style lang="scss">
.weui-picker {
  font-size: 18px;
}

.weui-select {
  height: 0.666667rem;
  line-height: 0.666667rem;
  padding-left: 0.4rem;
  padding-right: 0.4rem;
}

.weui-cell__ft::after {
  content: " ";
  display: inline-block;
  height: 6px;
  width: 6px;
  border-width: 0px 2px 2px 0;
  border-color: #c8c8cd;
  border-style: solid;
  -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
  transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
  position: relative;
  top: -2px;
  position: absolute;
  top: 50%;
  right: 15px;
  margin-top: -5px;
}

.action {
    padding: 0.6rem 0.4rem;
    padding-bottom: 0.2rem;
}

.action-delete {
    padding-top: 0;
    .weui-btn {
        border: 0;
        color: #ff5722;
        &:after {
            content: none
        }
    }
}
</style>
